from selenium import webdriver
import re                    # python's regular expression libarary
import requests      # html request
import os                   # file opreations
import pprint           # more standard print 
# 最近喜欢听粤语歌，一次一次下载太麻烦，所以写个脚本来自己下载，顺便练习python操作

import time 
import random  # 从可迭代对象中随机取一个
import getpass  # 非明文输入密码
import shutil       # 用于移动文件
# import numpy as np
from pyquery import PyQuery as pq
import platform # 识别操作系统
import argparse # 解析可选参数


'''
这是歌单类型的id和name的字典，想下载别的歌单请自行配置， 只需在运行该脚本时设置--tagid xxxxxx为下面对应的数字id即可
{
 '1000001599': '韩语',
 '1000001635': '经典老歌',
 '1000001670': '红歌',
 '1000001672': '流行',
 '1000001674': '摇滚',
 '1000001675': '中国风',
 '1000001681': '爵士',
 '1000001682': '电子',
 '1000001683': '乡村',
 '1000001694': '欢快',
 '1000001696': '怀旧',
 '1000001698': '爱情',
 '1000001699': '寂寞',
 '1000001700': '励志',
 '1000001703': '思念',
 '1000001749': '旅行',
 '1000001762': '国语',
 '1000001763': '粤语',
 '1000001766': '英语',
 '1000001767': '日语',
 '1000001775': '民谣',
 '1000001780': '儿童歌曲',
 '1000001783': '古典',
 '1000001795': '伤感',
 '1000001807': '纯音乐',
 '1000001808': 'R&amp;B',
 '1000001809': '嘻哈',
 '1000001827': 'KTV',
 '1000001851': '蓝调',
 '1000001852': '电子舞曲',
 '1000093923': '驾车',
 '1000587667': '期待',
 '1000587673': '小清新',
 '1000587677': '幸福',
 '1000587679': '减压',
 '1000587686': '夜店',
 '1000587688': '睡前安眠',
 '1000587689': '清晨',
 '1000587690': '夜晚',
 '1000587694': '散步',
 '1000587698': '游戏',
 '1000587702': '广场舞',
 '1000587706': '动漫',
 '1000587710': '治愈',
 '1000587712': '青春校园',
 '1000587717': '70后',
 '1000587718': '80后',
 '1000587726': '90后',
 '1001076078': '电视剧',
 '1001076080': '电影',
 '1001076083': '综艺',
 '1001076096': '网络热歌',
 '1002600579': '忧郁',
 '1002600585': '宣泄',
 '1002600588': '叛逆',
 '1002600606': '派对',
 '1003449615': '体育',
 '1003449723': '下午·茶',
 '1003449724': '小语种',
 '1003449726': '读书',
 '1003449727': '厂牌'
 }
'''

# -----配置参数
# 使用时log_user log_passwd driver_pth 是必须要配置的参数
# 如 python dwn_migu_music.py 13222222222 123123... 
parser = argparse.ArgumentParser(description='Music Download咪咕音乐歌单同步')
parser.add_argument('--maxpage', default='6', type=str, help='最大存储歌单页数,默认为6，可自己更改')
parser.add_argument('--pl_num', default='2', type=str, help='每次下载的歌单数量，默认为2')
parser.add_argument('log_user', default='', type=str, help='输入登录咪咕的用户名，可为手机邮箱')
parser.add_argument('log_passwd', default='',type=str, help='咪咕登录密码')
parser.add_argument('--dwn_sleep', default='10', type=str, help='每下一首歌分配的睡眠时间间隔，网速快可以设置小一点，默认10s')
parser.add_argument('--tagid', default='1000001763', type=str, help='自选下载歌单的类别，默认为{\'1000001763\': \'粤语\'}')
parser.add_argument('driver_pth', default='', type=str, help='输入你的ChromeDriver可执行文件的绝对路径，不懂去百度')
config = parser.parse_args()

pltype = config.tagid # playlist type
cwd = os.getcwd() # 得到当前目录
# TODO:解决了linux windows路径引发的下载问题
if platform.system() == 'Linux':
    root_directory = cwd + '/D_music_root'   # root directory of whole project
elif platform.system() == 'Windows':
    root_directory = cwd + '\\D_music_root'

music_save_path = os.path.join(root_directory, 'Playlists')           # Directory for musics　本地歌单的目录
html_save_path = os.path.join(root_directory, 'Html')              # Directory for saving html text 存放html文件目录
outer_list_path = os.path.join(html_save_path, 'outer_playlist_html')       # save local file for searching playlist info   歌单外部的html
inner_list_path = os.path.join(html_save_path, 'inner_playlist_html')        # save local file for searching musics under different playlists　歌单内的html

if not os.path.exists(root_directory):
    print('{} dir don\'t exist , will create soon '.format(root_directory))
    os.makedirs(root_directory)

if not os.path.exists(music_save_path):
    print('{} dir don\'t exist , will create soon '.format(music_save_path))
    os.makedirs(music_save_path)

if not os.path.exists(html_save_path):
    print('{} dir don\'t exist , will create soon '.format(html_save_path))
    os.makedirs(html_save_path)

if not os.path.exists(outer_list_path):
    print('{} dir don\'t exist , will create soon '.format(outer_list_path))
    os.makedirs(outer_list_path)

if not os.path.exists(inner_list_path):
    print('{} dir don\'t exist , will create soon '.format(inner_list_path))
    os.makedirs(inner_list_path)

if not os.path.exists(html_save_path + '/music_info'):
    os.makedirs(html_save_path + '/music_info')

if not os.path.exists(root_directory + '/music_tmp'):
    os.makedirs(root_directory + '/music_tmp')

# 先建立一些空数组和字典用于存放关键信息
SongId = []   # Song ID
SongName = [] # Song name
playlist_id = []   # Playlist id
playlist_name = []  # Playlist name
playlist_dict_ni = {}      # A empty dict to store {pname:p id}
playlist_dict_iu = {}     # A empty dict to store {pid: purl}
dwn_url_4_music = []


# 本函数用于爬去指定类别的所有歌单，并把页面内容保存在本地．
def get_plist_info():
    '''
    这个函数是在保存歌单页面，获取歌单id，name，最后保存到列表中
    而下载歌单时后面的函数是以每个歌单为单位的(一页上可能有很多歌单),而不是以一整页歌单为单位。
    在后续的操作中，歌单的id在本地的排序是按名称排列的(我没有实现把每一页的歌单放到一起)，而很多操作都需要去检索歌单id，所以
    当输入页数小于本地存储的页数时，按当前保存的最大页面去遍历。
    '''
    # outer_list_pages = int(input('输入本次想获取歌单页数,不要输入太大! (一页已经有24个不同的歌单了！):  '))  # this pages used for limiting max numbers of playlist info you got
    outer_list_pages = int(config.maxpage)
    for root, dirs, files in os.walk(outer_list_path):
        outer_page_nums_local = len(files)
        break

    if outer_list_pages < outer_page_nums_local:
        outer_list_pages = outer_page_nums_local
    else:
        pass
    # Get the playlist id and playlist name
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'} 

    # First get the outer playlist url and save to local txt file for later usage
    for page in range(0, outer_list_pages):
        url = 'https://music.migu.cn/v3/music/playlist'  # 用来爬歌单的url通式
        #list_type = '?tagId=' + dict[list_type]  TODO:想要实现字典映射，通过曲风类别转换到Id　从而组合成url
        # tagId = '?tagId=1000001763'         # TODO:如果想爬其他曲风，自己切换． 后期实现爬去不同类别的歌单
        tagId = '?tagId=' + config.tagid
        url_get = url + tagId + '&page={}'.format(page + 1)
        # If local file saved, then no need to request the html again!
        outer_list_fname = 'outer_pages[{}].txt'.format(page + 1)           # 定义本地保存的文件名格式　跟页数绑定
        if not os.path.exists(outer_list_path + '/' +  outer_list_fname):                          # 如果本地没有远程网页的backup,再去访问remote获取
            # imitate broswer http request
            print('URL Current Requesting(outer playlist):',url_get, end='\n')
            print('Saved to local file : {}'.format(outer_list_fname))
            html = requests.get(url=url_get, headers=headers)
            html.encoding = 'utf-8'
        # Save the HTML Text to local txt file           # Just for 粤语歌
            outer_html2list = list(html.text.split('\n'))
            outer_list = os.path.join(outer_list_path, outer_list_fname)
            with open(outer_list, 'w+', encoding='utf-8') as f:
                f.writelines(outer_html2list)
                f.close()              
    # 获取歌单信息
        local_hfile = outer_list_path + '/' +  outer_list_fname
        with open(local_hfile, 'rt', encoding='utf-8') as f:
            search_list = str(f.readlines())   # 打开文件用于正则匹配
            # pprint.pprint(search_list)
            plist_id = re.findall(r'<a href="/v3/music/playlist/(.{24}).*?"><img', search_list, re.S)  # 匹配歌单id
            # print('listid:')
            # pprint.pprint(plist_id)
            plist_name = re.findall(r'<a href="/v3/music/playlist/.{24}.*?" title="(.*?)">', search_list)  # 匹配歌单名字
            f.close()

        # Save playlist info to list
        playlist_name.extend(plist_name)     # playlist id to list
        playlist_id.extend(plist_id) # playlist name to list
    return playlist_id, playlist_name
################################################################################################################################


# 上面已经爬取到了歌单的id和name 下面生成每一个歌单的URL
playlist_url = []
def gen_plist_url(PlaylistID):
    # 通过PlaylistId生成各个歌单的url
    for id in PlaylistID:
        base_url = 'https://music.migu.cn/v3/music/playlist/'  # add / in the last
        playlist_id = id
        gen_list_url = str(base_url + playlist_id)
        playlist_url.append(gen_list_url)
    return playlist_url
#################################################################################################################################


####################################################Segmentation line#############################################################
# 建一个随机的headers字典
# headers = {
#         '1': "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
#         '2': "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
#         '3': "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0);",
#         '4': "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
#         '5': " Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
#         '6': "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
#         '7': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
#         '8': "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
#         '9': "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
#         '10': "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
#         '11': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
#         '12': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
#         '13': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
#         '14': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
#         '15': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
#         '16': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
#         '17': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
#         '18': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
#         '19': "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
#         '20': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
#         '21': "Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0"
# }


# # # 在每一个歌单下检索歌曲id 和歌曲名字 组合得到下载地址并保存到数组　TODO:歌单下面歌曲利用page不能翻页，需要模拟点击事件，点击下一页
def get_playlist_saved(playlist_ui):
    for id in playlist_ui:        # request the playlist url, get the music id and name.
        playlistID = id
        page = 0
        # rand =  str(np.random.randint(1,22))
        # valuE = list(headers[rand])
        # keY = list("User-Agent")
        # rand_header = dict(zip(keY, valuE))
         
        if not os.path.exists(inner_list_path + '/' + playlistID[:9]):
            os.mkdir(inner_list_path+'/'+playlistID[:9])

        for page in range(0, 2):
                if page <1:
                    Url =  playlist_ui[playlistID] + '?page={}'.format(page + 1)
                else:
                    Url = 'https://music.migu.cn/v3/music/playlist/' + playlistID[:9] + '?page={}'.format(page + 1)              # 因为第二页以后网页的格式不一样了

                headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0'} 
                inner_list_fname = playlistID[:9] + '_page_{}.txt'.format(page + 1)
                if not os.path.exists(inner_list_path + '/' + playlistID[:9] + '/' + inner_list_fname):              # 如果某个歌单某一页没有保存到本地，则去访问对应网址并保存
                    inner_list = os.path.join(inner_list_path, playlistID[:9],  inner_list_fname)
                    #####访问网页部分########
                    req = requests.get(url=Url, headers=headers)
                    sleep_time = random.randint(5, 12)      #随机睡眠时间
                    time.sleep(sleep_time)
                    req.encoding = 'utf-8'
                    print('URL Current Requesting:',Url, end='\n')
                    pprint.pprint('Saved to local file : {}'.format(inner_list_fname))
                    ########################
                    inner_html2list = list(req.text.split('\n'))
                    with open(inner_list, 'w+', encoding='utf-8') as f:
                        f.writelines(inner_html2list)
                        f.close()
    # 打印本地存在的歌单数量
    for root, dirs, files in os.walk(inner_list_path):
        playlists_num = len(dirs)
        break
    print('当前已存储 %d 页歌单， 累计  %d 个 ' % ((playlists_num / 24), playlists_num))
 ##########################################################################################


def get_music_info(PLAYLIST_ID):

    for each in PLAYLIST_ID:
        if not os.path.exists(html_save_path + '/music_info/' + str(each[:9])):
            os.makedirs(html_save_path + '/music_info/' + str(each[:9]))
    
    for root, dirs, files in os.walk(html_save_path + '/music_info'):
        fdname = dirs
        break
    
    for fdn in fdname:
        for i in range(0, 2):
            local_file = inner_list_path + '/' + fdn + '/' + fdn + '_page_{}.txt'.format(i + 1)
            with open(local_file, 'r+', encoding='utf-8') as f:
                search_list = str(f.readlines())
                music_id = re.findall(r'<a class="song-name-txt" href="/v3/music/song/(.{11}).*?" ', search_list)  #  Get the music_id under same playlist
                # pprint.pprint(music_id)
                music_name = re.findall(r'<a class="song-name-txt" href="/v3/music/song/.*?title="(.*?)"', search_list)  #    Get the music_name under the same playlist
                # pprint.pprint(music_name)
        SongId.extend(music_id)
        SongName.extend(music_name)
    return SongId, SongName


def gen_music_dwn_pth():

    music_cur_playlist = [] # 中间数组　用于过渡
    dwn_cur_playlist = [] # 用于保存每一个歌单下的歌曲下载地址
    dwn_pth_pre = 'https://music.migu.cn/v3/music/order/download/'

    for root, dirs, files in os.walk(inner_list_path):
        fdname = dirs
        break
    for fd in fdname:
        save_pth = os.path.join(html_save_path, 'music_info', str(fd))
        # 对于每个歌单，首先遍历下面的网页文件，找到所有的歌名
        for i in range(0, 2):
            check_file = inner_list_path + '/' + str(fd) + '/' + fd[:9] + '_page_{}.txt'.format(i + 1)
            with open(check_file, 'rt', encoding='utf-8') as f:
                search_list = str(f.readlines())
                f.close()
                music_under_list = re.findall(r'<a class="song-name-txt" href="/v3/music/song/(.{11}).*?" ', search_list)
                music_cur_playlist.extend(music_under_list)
            for each in music_cur_playlist:
                dwn_pth = dwn_pth_pre + str(each) + ' '         # 这里给正确的下载地址后面加了一个空格，便于后面分割
                dwn_cur_playlist.append(dwn_pth)
           
            local_fname = fd + '_music_pth.txt'
            local_file = save_pth + '/' + local_fname
            if not os.path.exists(save_pth + '/' + local_fname):
                os.path.join(save_pth, local_fname)
            with open(local_file, 'w', encoding='utf-8') as f1:
                f1.writelines(dwn_cur_playlist)
                f1.close()
            dwn_cur_playlist = []
        music_cur_playlist = [] # 遍历完一个歌单就置空
        
        total_music_dwn_info = len(fdname)
    print('All {} music_infos under different playlists are saved!'.format(total_music_dwn_info))   


#####################################################################


def get_log_info():
    print('现在进行咪咕音乐的登录！')
    # username = input('输入手机号/邮箱/用户名: ')
    # passwd = getpass.getpass("输入密码: ")
    username = config.log_user
    passwd = config.log_passwd
    time.sleep(1)
    return username, passwd


def isElementExists(querypath,driver):
    try:
        driver.find_element_by_class_name('Validform_checktip')
        return True
    except:
        return False


def relog(driver):
        browser = driver
        print('用户名或者密码输入有误，请重试！') 
        time.sleep(1)
        username = input('重新输入用户名: ')
        browser.find_element_by_id('J_AccountPsd').clear()  # 清空原用户名
        time.sleep(1)
        browser.find_element_by_id('J_AccountPsd').send_keys(username) # 输入用户名
        passwd = getpass.getpass('重新输入密码: ')
        lg_passwd = browser.find_element_by_id('J_PasswordPsd').clear()
        time.sleep(1)
        lg_passwd = browser.find_element_by_id('J_PasswordPsd').send_keys(passwd)           #输入密码
        browser.execute_script('document.querySelector("body > div.loginhome-other > div.form-login.J_FormLogin.formLoginW > form.J_ValidPsdForm.msgLogin_b > div > div.form-item.form-item0 > input").click()')
        time.sleep(1)
        browser.refresh()


def log_on(browser):

    username, passwd = get_log_info()   #获取登录信息

    request_url = 'https://music.migu.cn/v3/music/playlist?tagId=1000001763'  # 先访问粤语歌单，然后登陆
    browser.get(request_url)
    browser.set_window_size(1920, 1080)
    browser.refresh()
    time.sleep(1)
    log_icon = browser.find_element_by_id('J_login')  #右上角登陆图标
    log_icon.click()
    browser.switch_to_window(browser.current_window_handle)
    time.sleep(1)
    log_button = browser.find_element_by_id('J-popup-login')  
    # 登陆按钮
    log_button.click()
    time.sleep(1)
    browser.switch_to_frame('loginIframe53645') # 切换iframe
    browser.find_element_by_xpath('/html/body/div[2]/div[1]/div[1]/ul/li[2]/span').click()  # 使用密码登录
    lg_username = browser.find_element_by_id('J_AccountPsd')    # 用户名
    lg_username.send_keys(username) # 输入用户名
    time.sleep(2)
    # 验证码登录模块
    # lg_get_code_verify = browser.find_element_by_id('J_GetMsgCodeOne')  # 发送验证码
    # lg_get_code_verify.click()
    # passwd = input('Input your verification code(6 digits): ')
    # time.sleep(15)
    lg_passwd = browser.find_element_by_id('J_PasswordPsd')
    lg_passwd.send_keys(passwd)           #输入密码
    time.sleep(3)
    browser.execute_script('document.querySelector("body > div.loginhome-other > div.form-login.J_FormLogin.formLoginW > form.J_ValidPsdForm.msgLogin_b > div > div.form-item.form-item0 > input").click()')
    time.sleep(3)
    if isElementExists(querypath='/html/body/div[2]/div[1]/div[2]/span/text()', driver=browser):
        relog(driver=browser)
    else:
        time.sleep(3)
        browser.refresh()
        print('登录成功！')
        # browser.switch_to.default_content()


def req_music_dwn_url(music_info_path,  music_save_path, music_dwn_path, chromedriver_path):
    '''
    music_info_path: 放音乐下载地址的根目录
    music_dwn_path: 暂时下载音乐的根目录        
    music_save_path: 存放下载音乐的根目录

    '''
    # ------- 登录模块 
    prefs = {'profile.default_content_settings.popups': 0, #防止保存弹窗
'download.default_directory':music_dwn_path,#设置默认下载路径
"profile.default_content_setting_values.automatic_downloads":1#允许多文件下载
}
    option = webdriver.ChromeOptions()
    option.add_experimental_option("detach", True) #登录后不关闭页面
    option.add_experimental_option('prefs', prefs)  # 设置下载目录
    option.add_argument('headless') # 不打开浏览器进行操作
    browser = webdriver.Chrome(executable_path=chromedriver_path, options = option)

    log_on(browser=browser) #登录

# -------   LOG ON MODULE ENDED!-----------

    m_i_p = music_info_path
    m_s_p = music_save_path
    m_d_p = music_dwn_path
    for root, dirs, files in os.walk(m_i_p):
        fdname = dirs
        break
    # 遍历每一个歌单
    fdname = fdname
    num = 0
    # stop_n = int(input('输入你想下载的歌单数量 1-{}(在这个范围之间): '.format(len(fdname))))
    stop_n = int(config.pl_num)
    if stop_n > len(fdname):
        print('输入的歌单数量大于本地保存的歌单数，请重新输入 当前本地保存歌单{}个'.format(len(fdname)))
    else:
        reverse_rename2id(root_fd=m_s_p)        # before downloading, reversely change the renamed chinese fd to its id.
        for fd in fdname:
            if num < stop_n:
                # 首先生成下载目录的文件夹　（每一个歌单都独立）
                if not os.path.exists(m_s_p + '/' + fd):
                    os.makedirs(m_s_p + '/' + fd)
                # if fd under playlists are empty, continue to download
                if os.listdir(m_s_p + '/' + fd) == [] and os.path.exists(m_s_p + '/' + fd): 
                    dwn_info_file = music_info_path + '/' + fd + '/' + fd + '_music_pth.txt'
                    with open(dwn_info_file, encoding='utf-8') as f:
                        f2str = f.readlines()[0]
                        f2str_len = len(f2str)
                        f.close()
                        url_dwn = []  # 暂存每一个歌单下的下载地址
                        for i in range(int(f2str_len / 58)):
                            url = f2str[i*58:(i + 1)*58]        # 每58个字符为一个下载地址
                            if re.findall()
                            if not url in url_dwn:                 #避免下载到重复的歌，如果下载列表里不存在当前下载地址，则append
                                url_dwn.append(url)
                    #得到无重复的下载列表，开始下载
                    count = 0
                    for per_url in url_dwn:
                        browser.get(per_url)
                        if not browser.find_element_by_id('error'):
                            browser.refresh()
                            time.sleep(1)
                            url = browser.page_source
                            parsed_html = str(pq(url))
                            cur_songname = re.findall(r'<a href="/v3/music/song/.*?" target="_blank">(.*?)</a>', parsed_html)
                            print('当前歌曲名: ',cur_songname[0])

                            tmp_music = os.listdir(m_d_p)
                            if tmp_music != []:       # 如果当前临时下载目录有歌曲 检索是哪首歌
                                # --------遍历本地歌曲缓存
                                check_bit = 0
                                for fname in tmp_music:
                                    if fname.find(cur_songname[0]) != -1:   # 本地文件中如果匹配到当前歌曲名
                                        check_bit = check_bit or 1      #或操作来识别本地到底有没有当前歌曲
                                    else:
                                        check_bit = check_bit or 0
                                if check_bit:   # 如果本地有这个歌曲，那么就跳过下载
                                    count += 1
                                    print('当前歌曲本地已下载！2s后进行下一歌曲下载')
                                else:
                                    browser.execute_script('document.querySelector("#J_query").click()')
                                    count += 1
                                    print('当前歌单id-{}, 正在下载第{}首，剩余{}首'.format(fd, count, len(url_dwn) - count))
                                    time.sleep(int(config.dwn_sleep))
                            # ------- 如果本地下载缓存为空 直接去网页下载        
                            else:
                                browser.execute_script('document.querySelector("#J_query").click()')
                                # rand_list = list(range(25,31))      # 随机睡眠时间25-30s  网速快完全可以把这个调小一点，但是不介意调太小
                                # rand_choice = random.choice(rand_list)
                                count += 1
                                print('当前歌单id-{}, 正在下载第{}首，剩余{}首'.format(fd, count, len(url_dwn) - count))
                                time.sleep(int(config.dwn_sleep))
                            else:
                                print('当前下载地址有误，1s后跳过')
                                time.sleep(1)

                    print('All {} musics under playlist-{} are downloaded!!! '.format(len(url_dwn) , fd))
                    url_dwn = [] # 下载完一个歌单就清空该列表
                    mv_to_playlist_fd(fd=fd, m_s_p=m_s_p, m_d_p=m_d_p) # 调用函数将下载的歌曲转移到对应的歌单中
                    num += 1    # 每下载完一个歌单就+1
                #-- 如果save_path下存在对应歌单id的文件夹，那么他已经下载完了 直接跳过
                else:
                    pass
            # ---超出指定的stop_n -> pass
            else:
                pass
        # 遍历完stop_n个歌单
        time.sleep(3)
        browser.quit( )     # 关闭浏览器
        print('##All {} playlists\' musics are downloaded and  moved to playlist folder!!!##'.format(stop_n))



def mv_to_playlist_fd(fd,m_s_p, m_d_p):
    '''
    本函数作用为把req_music_dwn_url() 函数请求下载的歌曲，转移到我们指定好的本地歌单下面
    '''
    src_path = m_d_p  # 当前下载歌曲的目录
    des_path = os.path.join(m_s_p, fd)  #要转移到的目的地址
    for root, dirs, files in os.walk(src_path):
        files = files
        break
    for each in files:
        if each[-4:] == '.mp3':
            src_file = os.path.join(src_path, each)
            shutil.move(src_file, des_path) # 将文件从源路径转移到目标路径
        else:
            pass
                

def rename2chinese(root_fd):
    '''
    本函数实现歌单name转换成对应的中文名，实现本地与migu网页上的一致．．．．
    通过之前建立的playlist_dict_ni来转换
    '''

    for root, dirs, files in os.walk(root_fd):
        need_rename_fd = dirs
        break
    for fd in need_rename_fd:
        for item in playlist_dict_ni:
            if playlist_dict_ni[item][:9] == fd:
                os.rename(root_fd+'/'+fd, root_fd+'/'+item)
            else:
                pass


def reverse_rename2id(root_fd):
    '''
    reversely rename chinese playlise name to format:id,  to check if there are some playlists are alreay downloaded.
    '''
    for root, dirs, files in os.walk(root_fd):
        need_revrse_fd = dirs
        break
    # retrieve the local playlist fd, reversely rename the chinese fd to its id before download other playlists.
    for fd in need_revrse_fd:
        for item in playlist_dict_ni:
            # if the playlists chinese name == the names in dict, then reversely rename it to its id.
            if item == fd:
                os.rename(root_fd + '/' +fd, root_fd + '/' + playlist_dict_ni[item][:9])
            else:
                pass
# 函数执行部分


# 网页信息爬取部分
###############################################################################
get_plist_info()    # 获取歌单信息
gen_plist_url(PlaylistID=playlist_id) # 获取歌单url

playlist_dict_iu = dict(zip(playlist_id, playlist_url))      # 生成playlistid和playlisturl的字典映射
playlist_dict_ni = dict(zip(playlist_name, playlist_id)) # name和id的字典映射关系

# pprint.pprint(playlist_dict_ni)

get_playlist_saved(playlist_dict_iu)    # 获取歌曲信息
get_music_info(playlist_id)                 # 获取歌曲url

gen_music_dwn_pth()                           # 生成music_dwn_pth在html_save_path + '/music_info' 目录下

################################################################################
# 歌曲下载部分
#####################################################
# log_on()    # 登录网站  TODO:已实现！

# 下载歌曲
req_music_dwn_url(
music_info_path= './D_music_root/Html/music_info',                                       
music_save_path=music_save_path,
music_dwn_path=os.path.join(root_directory, 'music_tmp'),
chromedriver_path=config.driver_pth)      # 谷歌driver的执行位置，

rename2chinese(root_fd=music_save_path)
